package Hot100;

public class 在排序数组中查找元素的第一个和最后一个位置 {
    public int[] searchRange(int[] nums, int target) {
        int[] res = new int[]{-1, -1};
        int left = binarySearch(nums, target - 0.5), right = binarySearch(nums, target + 0.5) - 1;
        if (left < nums.length && nums[left] == target) res[0] = left;
        if (right >= 0 && nums[right] == target) res[1] = right;
        return res;
    }

    public int binarySearch(int[] nums, double target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target) left = mid + 1;
            else right = mid - 1;
        }
        return left;
    }
}
